#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Simple Connector - Easy connection tool for 101.37.80.173:8888
"""

import socket
import sys
import threading
import time

# 导入安全属性访问器
try:
    from core.safe_attribute_accessor import safe_getattr, safe_hasattr
except ImportError:
    # 如果导入失败，提供简单的备用实现
    def safe_getattr(obj, attr, default=None):
        return getattr(obj, attr, default)
    
    def safe_hasattr(obj, attr):
        return hasattr(obj, attr)

class SimpleConnector:
    def __init__(self, target_ip="101.37.80.173", target_port=8888):
        self.target_ip = target_ip
        self.target_port = target_port
        self.sock = None
        self.connected = False
        
    def connect(self):
        """Connect to target server"""
        try:
            print(f"Connecting to {self.target_ip}:{self.target_port}...")
            
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.sock.settimeout(10)
            
            self.sock.connect((self.target_ip, self.target_port))
            self.connected = True
            
            print(f"✓ Connected successfully to {self.target_ip}:{self.target_port}")
            return True
            
        except Exception as e:
            print(f"✗ Connection failed: {e}")
            return False
    
    def send_command(self, command):
        """Send command to target"""
        if not self.connected or not self.sock:
            print("Not connected to target")
            return False
            
        try:
            # Send command
            self.sock.send((command + "\n").encode())
            print(f"Command sent: {command}")
            
            # Receive response (with timeout)
            self.sock.settimeout(5)
            response = self.sock.recv(4096).decode('utf-8', errors='ignore')
            
            if response:
                print("Response:")
                print(response)
            else:
                print("No response received")
                
            return True
            
        except socket.timeout:
            print("Timeout waiting for response")
            return False
        except Exception as e:
            print(f"Error sending command: {e}")
            self.connected = False
            return False
    
    def interactive_mode(self):
        """Interactive command mode"""
        print("\n=== Interactive Mode ===")
        print("Type commands to send to target (type 'quit' to exit)")
        print("-" * 40)
        
        while self.connected:
            try:
                command = input("$ ")
                
                if command.lower() in ['quit', 'exit']:
                    break
                    
                if command.strip():
                    if not self.send_command(command):
                        print("Connection lost. Attempting to reconnect...")
                        if self.connect():
                            self.send_command(command)
                        else:
                            break
                            
            except KeyboardInterrupt:
                print("\nExiting...")
                break
            except Exception as e:
                print(f"Error: {e}")
                break
    
    def disconnect(self):
        """Disconnect from target"""
        if self.sock:
            try:
                self.sock.close()
            except:
                pass
        self.connected = False
        print("Disconnected")

def main():
    """Main function"""
    print("Simple Connector for 101.37.80.173:8888")
    print("=" * 40)
    
    connector = SimpleConnector()
    
    # Connect to target
    if connector.connect():
        try:
            # Start interactive mode
            connector.interactive_mode()
        finally:
            connector.disconnect()
    else:
        print("Failed to connect to target")
        sys.exit(1)

if __name__ == "__main__":
    main()